<template>
    <el-container>
        <el-main>
            <el-form ref="productForm" :model="form" label-width="90px">

                <div style="display: flex">
                    <el-form-item label="空桶名称" style="width: 500px" prop="name" :rules="{ required: true, message: '请输入空桶名称', trigger: 'blur' }">
                        <el-input v-model="form.name" />
                    </el-form-item>
                </div>

              <div style="display: flex">
                <el-form-item label="空桶押金" prop="price" style="width: 190px" :rules="{ required: true, message: '请输入空桶押金', trigger: 'blur' }">
                  <el-input v-model="form.price" />
                </el-form-item>
              </div>

              <el-form-item label="空桶图标" style="width: 600px">
                <single-upload v-model="thumbnail"></single-upload>
              </el-form-item>

                <div style="display: flex">

                    <el-form-item label="空桶标签" style="width: 600px">
                        <el-select v-model="tagIds" style="width: 100%" multiple placeholder="请选择">
                            <el-option v-for="(item,index) in tagOptions" :key="index" :label="item.name" :value="item.id" />
                        </el-select>
                    </el-form-item>
                </div>

                <el-form-item>
                    <el-button style="margin-top: 30px" type="primary" :loading="clicked" @click="editProduct('productForm')">
                        &nbsp&nbsp完 成&nbsp&nbsp
                    </el-button>
                </el-form-item>

            </el-form>
        </el-main>
    </el-container>
</template>
<style lang="scss" scoped>
.photo-content {
    width: 100%;
    display: flex;
    align-items: flex-end;
    border-top: 1px #eee solid;
    margin-bottom: 20px;
    margin-top: 10px;
}
/deep/.el-input__inner {
    padding: 0 5px;
}
/deep/ .el-upload--picture-card {
    width: 50px !important;
    height: 50px !important;
    line-height: 50px !important;
    text-align: center;
    .menu-wrapper {
        margin: 15px;
    }
}
</style>
<script>
import { mapGetters } from "vuex";
import { list as vipList } from "@/api/vip";
import permission from "@/directive/permission/index.js"; // 权限判断指令
import elDragDialog from "@/directive/el-drag-dialog"; // base on element-ui
import { EventBus } from "@/api/eventBus";
import utils from "../../utils/utils.js";
import { find, update } from "@/api/product";
import { list as tagList } from "@/api/tag";
import SingleUpload from "@/components/Upload/singleUpload";
import { list as distributionList } from "@/api/distribution.js";
export default {
    name: "product-edit",
    directives: { elDragDialog, permission },
    filters: {},
    components: {
        SingleUpload
    },
    data() {
        return {
            thumbnail:"",
            id: "",
            length: 0,
            times: null,
            isCount: true,
            clicked: false, // 按钮防双击
            subscribe: false,
            market: false,
            typeDisabled: false,
            form: {
                maxLimit: "",
                publishType: 0,
                id: "",
                name: "",
                productCategoryId: "",
                shortName: "",
                orders: "",
                type: "1",
                freightId: "",
                shippingMethod: "0,1,2",
                isMarketable: false,
                subTitle: "",
                minLimit: "",
                // labal: '',
                quality: "",
                distributionId: "",
                brandId: "",
                stock: "",
                supplierId: "",
                allocatedStock: "",
                weight: "",
                goodsId: "",
                price: "",
            },
            tagIds: [],
            disOptions: [],
            tagOptions: [],
            freightNames: [],
            brandLoading: false,
            freightLoading: false,
            brandVisible: false,
            barrelOptions: [],
            suppOptions: [],
            suppLoading: false,
            suppVisible: false,
            supplierName: "",
            brandName: "",
            productList: [
                {
                    isClick: false,
                    isFirst: true,
                    maxLimit: "",
                    length: 0,
                    publishType: 0,
                    isList: true,
                    name: "",
                    productCategoryId: "",
                    shortName: "",
                    orders: 0,
                    type: "1",
                    freightId: "",
                    isMarketable: false,
                    subTitle: "",
                    minLimit: "",
                    // labal: '',
                    quality: "",
                    isChose: false,
                    isCount: false,
                    distributionId: "",
                    brandId: "",
                    stock: "",
                    supplierId: "",
                    allocatedStock: "",
                    weight: "",
                    subType: 3,
                    shippingMethod: "0,1,2",
                    // ------
                    sn: "",
                    thumbnail: "",
                    spec1: 0,
                    spec2: 0,
                    unit: 0,
                    unitRate: 0,
                    marketPrice: 0,
                    price: "",
                    cost: 0,
                    point: 0,
                    unitType: "",
                    vip1price: "",
                    vip2price: "",
                    vip3price: "",
                    vip4price: "",
                    vip5price: "",
                    article: {
                        productMeta: {
                            images: [],
                            video: "",
                            label: "",
                        },
                        content: "",
                    },
                },
            ],
            type: null,
        };
    },
    watch: {
        // 路由地址不变的情况下,如果id变化则重新获取数据
        $route(newVal, oldVal) {
            console.log(newVal);
            if (newVal.name == "pledge-edit" && newVal.query.id != this.id) {
                this.getFindData();
            }
        },
    },
    computed: {
        ...mapGetters(["scoreType"]),
    },
    created() {
        this.loadTag();
        this.getFindData();
    },
    activated() {},
    methods: {
        getFindData() {
            this.times = new Date().getSeconds();
            this.id = this.$route.query.id;
            var _this = this;
            find(this.id)
                .then((response) => {
                    console.log(response);
                    _this.article = response.data.article;
                    _this.length = response.data.products.length - 1;
                    for (var k = 0; k < response.data.products.length; k++) {
                        this.length = k;
                        response.data.products[k]["length"] = this.length;
                    }
                    for (var i = 1; i < response.data.products.length; i++) {
                        if (response.data.products[i].unitType == 2) {
                            response.data.products[i]["isCount"] = false;
                        } else {
                            response.data.products[i]["isCount"] = true;
                        }
                        if (response.data.products[0].unitType == 0) {
                            response.data.products[i]["isClick"] = true;
                            response.data.products[i]["isChose"] = true;
                        } else {
                            response.data.products[i]["isClick"] = false;
                            response.data.products[i]["isChose"] = false;
                        }
                    }

                    response.data.products[0]["isFirst"] = true;

                    _this.productList = response.data.products;
                    _this.tagIds = [];
                    if (!utils.isNull(this.productList[0].tags)) {
                        _this.productList[0].tags.forEach(function (item) {
                            _this.tagIds.push(item.id);
                        });
                    }

                    this.productList.forEach((item) => {
                        if (item.isList) {
                            this.form.maxLimit = item.maxLimit;
                            this.form.id = item.id;
                            this.form.name = item.name;
                            this.categoryName = item.productCategoryName;
                            this.form.productCategoryId =
                                item.productCategoryId;
                            this.form.shortName = item.shortName;
                            this.form.orders = item.orders;
                            this.form.publishType = item.publishType;
                            this.thumbnail = item.thumbnail;
                            this.form.type = 1;

                            this.form.subType = 3;

                            this.form.isMarketable = item.isMarketable;
                            this.form.subTitle = item.subTitle;
                            this.form.minLimit = item.minLimit;
                            // this.form.labal = item.labal;
                            this.form.quality = item.quality;
                            this.form.distributionId = item.distributionId;
                            this.form.brandId = item.brandId;
                            this.form.stock = item.stock;
                            this.form.supplierId = JSON.stringify(
                                item.supplierId
                            );
                            this.form.allocatedStock = item.allocatedStock;
                            this.form.weight = item.weight;
                            this.form.price = item.price;
                            this.form.goodsId = item.goodsId;
                            this.form.freightId = item.freightId;
                        }
                    });
                    this.supplierName = response.data.supplierName;
                    this.brandName = response.data.brandName;
                    console.log(_this.form);
                })
                .catch((error) => {
                    console.log(error.content);
                });
        },
        loadDistribution() {
            distributionList()
                .then((res) => {
                    this.disOptions = res.data.data;
                })
                .catch((err) => {
                    console.log(err);
                });
        },

        compare(property, desc) {
            return function (a, b) {
                var value1 = a[property];
                var value2 = b[property];
                if (desc == true) {
                    // 升序排列
                    return value1 - value2;
                } else {
                    // 降序排列
                    return value2 - value1;
                }
            };
        },

        loadTag() {
            const _this = this;
            const params = new URLSearchParams();
            params.append("pageNum", 1);
            params.append("pageSize", 1000);
            params.append("type", 3);
            tagList(params)
                .then((response) => {
                    console.log(response);
                    _this.tagOptions = response.data.data;
                })
                .catch((error) => {});
        },

        editProduct(form) {
            const _this = this;
            this.$refs[form].validate((valid) => {
                if (valid) {
                    // 校验表单
                    _this.clicked = true;
                    const params = new URLSearchParams();
                    _this.tagIds.forEach(function (item) {
                        params.append("tagIds", item);
                    });
                    if (
                        this.productList[0].unitType != 0 &&
                        this.productList.length == 1
                    ) {
                        _this.$message({
                            message: "已启用多单位，商品规格不足",
                            type: "error",
                        });
                        _this.clicked = false;
                        return;
                    }
                    for (let i = 0; i < _this.productList.length; i++) {
                        delete this.productList[i].length;
                        if (this.productList[i].hasOwnProperty("isFirst")) {
                            delete this.productList[i].isFirst;
                        }
                        if (this.productList[i].hasOwnProperty("isChose")) {
                            delete this.productList[i].isChose;
                        }
                        if (this.productList[i].hasOwnProperty("isCount")) {
                            delete this.productList[i].isCount;
                        }
                        if (this.productList[i].hasOwnProperty("isClick")) {
                            delete this.productList[i].isClick;
                        }
                        _this.productList[i].name = _this.form.name;
                        _this.productList[i].productCategoryId =
                            _this.form.productCategoryId;
                        _this.productList[i].shortName = _this.form.shortName;
                        _this.productList[i].orders = _this.form.orders;
                        _this.productList[i].type = 1;
                        _this.productList[i].subType = 3;

                        _this.productList[i].publishType =_this.form.publishType;
                        _this.productList[i].isMarketable = false;
                        _this.productList[i].freightId = _this.form.freightId;
                        _this.productList[i].subTitle = _this.form.subTitle;
                        _this.productList[i].minLimit = _this.form.minLimit;
                        _this.productList[i].maxLimit = _this.form.maxLimit;
                        _this.productList[i].quality = _this.form.quality;
                        _this.productList[i].distributionId =
                            _this.form.distributionId;
                        _this.productList[i].brandId = _this.form.brandId;
                        _this.productList[i].supplierId = _this.form.supplierId;
                        _this.productList[i].allocatedStock =
                            _this.form.allocatedStock;
                        _this.productList[i].weight = _this.form.weight;
                        _this.productList[i].price = _this.form.price;
                        _this.productList[i].goodsId = _this.form.goodsId;
                        _this.productList[i].article = _this.article;
                        _this.productList[i].thumbnail = _this.thumbnail;
                        if (
                            parseInt(_this.productList[i].minLimit) != 0 &&
                            parseInt(_this.productList[i].maxLimit) != 0 &&
                            parseInt(_this.productList[i].minLimit) >
                                parseInt(_this.productList[i].maxLimit)
                        ) {
                            _this.$message({
                                message: "最小订购量不可大于每日限量",
                                type: "success",
                            });
                            _this.clicked = false;
                            return;
                        }

                        if (utils.isNull(_this.productList[i].unit)) {
                            _this.productList[i].unit = "件";
                        }
                        if (utils.isNull(_this.productList[i].unitRate)) {
                            _this.productList[i].unitRate = 1;
                        }
                        if (utils.isNull(_this.productList[i].thumbnail)) {
                            _this.productList[i].thumbnail =
                                "http://cdn.rzico.com/weex/resources/images/defaultProduct.png";
                        }
                        if (utils.isNull(_this.productList[i].weight)) {
                            _this.productList[i].weight = 0;
                        }
                        if (utils.isNull(_this.productList[i].allocatedStock)) {
                            _this.productList[i].allocatedStock = 0;
                        }
                        if (utils.isNull(_this.productList[i].stock)) {
                            _this.productList[i].stock = 0;
                        }
                        if (utils.isNull(_this.productList[i].quality)) {
                            _this.productList[i].quality = 0;
                        }
                        if (
                            utils.isNull(_this.productList[i].minLimit) ||
                            _this.productList[i].minLimit < 1
                        ) {
                            _this.productList[i].minLimit = 1;
                        }
                        if (utils.isNull(_this.productList[i].marketPrice)) {
                            _this.productList[i].marketPrice = 0;
                        }
                        if (utils.isNull(_this.productList[i].price)) {
                            _this.productList[i].price = 0;
                        }
                        if (utils.isNull(_this.productList[i].cost)) {
                            _this.productList[i].cost = 0;
                        }
                        if (utils.isNull(_this.productList[i].vip1price)) {
                            _this.productList[i].vip1price = 0;
                        }
                        if (utils.isNull(_this.productList[i].vip2price)) {
                            _this.productList[i].vip2price = 0;
                        }
                        if (utils.isNull(_this.productList[i].vip3price)) {
                            _this.productList[i].vip3price = 0;
                        }
                        if (utils.isNull(_this.productList[i].vip4price)) {
                            _this.productList[i].vip4price = 0;
                        }
                        if (utils.isNull(_this.productList[i].vip5price)) {
                            _this.productList[i].vip5price = 0;
                        }
                        if (utils.isNull(_this.productList[i].point)) {
                            _this.productList[i].point = 0;
                        }
                    }
                    console.log(this.productList);
                    update(_this.productList, params)
                        .then((response) => {
                            console.log(response);
                            _this.clicked = false;
                            EventBus.$emit("pledge-edit", response.data[0]);
                            _this.$store
                                .dispatch("tagsView/delView", _this.$route)
                                .then(({ visitedViews }) => {
                                    _this.$router.push({
                                        path: "/pledge/list",
                                    });
                                }); // 关闭当前tab回到列表
                        })
                        .catch((error) => {
                            _this.clicked = false;
                        });
                } else {
                    console.log("error submit!!");
                    return false;
                }
            });
        },

    },
};
</script>
